#! -*- coding:utf-8 -*-
import logging
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from common.channel.db import get_channel_status, set_channel_status
from common.order.db import get_total_mount

_LOGGER = logging.getLogger(__name__)

CHANNELS = [{
    'channel_id': 218,
    'name': u'witch自有支付宝',
    'day_max_pay': 49000,
}, ]


def handle_channel(channel_id, max_amount):
    # 读取通道状态
    now = datetime.utcnow() + timedelta(hours=8)
    start = datetime.strptime("{}-{}-{} 0:0:0".format(now.year, now.month,now.day), "%Y-%m-%d %H:%M:%S")
    start = start + timedelta(hours=-8)
    end = (start + timedelta(days=1))
    status = get_channel_status(channel_id)
    _LOGGER.info("pay_channel_control %s %s %s", start, end, status)
    total = get_total_mount(channel_id, start, end)
    _LOGGER.info("pay_channel_control channel_id:%s, now: %s, status:%s, total:%s", channel_id, now, status, total)
    # 早上5点到6点之间 如果 通道状态为关闭，并且支付总金额没有到达上限，打开通道
    # 0:不可用 1:可用
    if now.hour == 5 and status == 0 and total < max_amount:
        set_channel_status(channel_id, 1)
        return
    if total >= max_amount and status == 1:
        set_channel_status(channel_id, 0)

class Command(BaseCommand):
    def handle(self, **options):
        for c in CHANNELS:
            handle_channel(c['channel_id'], c['day_max_pay'])
